/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UserBN;

import DataAccess.FindResult;
import DataAccess.UserDA;
import entity.SwhUser;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Mr-Quick
 */
public class UserService {

    EntityManager em;

    public UserService() {
        String persistenceUnitName = "SweetHomePU";
        EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnitName);
        em = factory.createEntityManager();
    }

    public void register(SwhUser u) {
        try {
            UserDA da = new UserDA(em);
            em.getTransaction().begin();
            da.create(u);
            em.getTransaction().commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public boolean checkExistedEmail(String emailValue) {
        Query q = em.createQuery("SELECT s FROM SwhUser s WHERE s.email = :email", SwhUser.class);
        q.setParameter("email", emailValue);
        List<SwhUser> users = q.getResultList();
        if (users.size() != 0) {
            return true;
        } else {
            return false;
        }

    }
    public entity.SwhUser findAccountByUsername(String username) {
        UserDA userDA = new UserDA(em);
        FindResult<SwhUser> users = userDA.findAbsolutely("account", username);
        if (users.isEmpty()) {
            return null;
        } else {
            return users.get(0);
        }
    }
    
    public entity.SwhUser findAccountByIduser(String iduser) {
        UserDA userDA = new UserDA(em);
        FindResult<SwhUser> users = userDA.findAbsolutely("iDUser", iduser);
        if (users.isEmpty()) {
            return null;
        } else {
            return users.get(0);
        }
    }
    
    
}
